import { ElTag, type TagProps } from 'element-plus'
import {
  WARNING_LEVELS_TEXT,
  WARNING_STATES_TEXT,
  calculateTheLastTime,
  joinThresoldValue,
  joinWarningValue,
} from './helper'
import { uuid } from '@/utils'
import { PAGE_SIZES } from '@/constant/modules/paging'
import type { TableColumn, WarningInfo } from '@/types'

import { alarmApi } from '@/api'

/**
 * @mixin 查询实时告警或告警历史信息
 */
export function useWarningList() {
  const [loading, setLoading] = useState(true)
  const [lists, setLists] = useShallowState<WarningInfo[]>(
    [],
  )
  const columns: TableColumn<WarningInfo>[] = reactive([
    {
      key: uuid(),
      label: '告警类型',
      prop: 'warningType',
      sortable: true,
      fixed: 'left',
      minWidth: 120,
      render({ row }) {
        return renderType(row)
      },
    },
    {
      key: uuid(),
      label: '指标名称',
      prop: 'indicatorName',
      sortable: true,
      // hidden: true,
      minWidth: 160,
      fixed: 'left',
    },
    {
      key: uuid(),
      label: '指标编码',
      prop: 'indicatorNumber',
      minWidth: 140,
      fixed: 'left',
    },
    {
      key: uuid(),
      label: '测点点位号',
      prop: 'indicatorCode',
      // hidden: true,
      minWidth: 120,
    },
    {
      key: uuid(),
      label: '阈值下限-上限',
      prop: 'thresholdValue',
      minWidth: 180,
    },
    {
      key: uuid(),
      label: '告警值',
      prop: 'warningValue',
      sortable: true,
      minWidth: 140,
    },
    {
      key: uuid(),
      label: '设备名称/点位',
      prop: 'pointNameFull',
      minWidth: 160,
    },
    {
      key: uuid(),
      label: '告警状态',
      prop: 'state',
      sortable: true,
      minWidth: 120,
      render({ row }) {
        return renderState(row)
      },
    },
    {
      key: uuid(),
      label: '告警开始时间',
      prop: 'warningStartTime',
      sortable: true,
      minWidth: 160,
    },
    {
      key: uuid(),
      label: '告警持续时间',
      prop: 'warningLastTime',
      sortable: true,
      minWidth: 160,
      render({ row }) {
        return h(
          'span',
          calculateTheLastTime(row.warningStartTime),
        )
      },
    },
    {
      key: uuid(),
      label: '告警内容',
      prop: 'warningContent',
      // hidden: true,
      minWidth: 160,
    },
    { key: uuid(), label: '工单号', prop: 'workOrderNum', minWidth: 120 },
  ])
  const pagination = reactive({
    pageNumber: 1,
    pageSize: PAGE_SIZES[0]!,
    total: 0,
  })

  async function getLists(
    paramsFn: (
      pageNumber: number,
      pageSize: number
    ) => alarmApi.SelectWarningPageParams,
  ) {
    const { pageNumber, pageSize } = pagination
    const params = paramsFn(pageNumber, pageSize)
    setLoading(true)
    try {
      const { data } = await alarmApi.selectWarningPage(
        params,
      )
      data.records?.forEach((v) => {
        // 阈值上下限
        v.thresholdValue = joinThresoldValue(
          v.thresholdValueUp,
          v.thresholdValueDown,
          v.unit,
        )
        // 监测值（带单位）
        v.warningValue = joinWarningValue(
          +v.warningValue,
          v.unit,
        )
      })
      setLists(data.records || [])
      pagination.total = data.total
    }
    catch (e) {
      console.log(e)
    }
    finally {
      setLoading(false)
    }
  }

  async function handleDownload(
    paramsFn: (
      pageNumber: number,
      pageSize: number
    ) => alarmApi.SelectWarningPageParams,
  ) {
    const { pageNumber, pageSize } = pagination
    const params = paramsFn(pageNumber, pageSize)
    try {
      const { data } = await alarmApi.exportWarning(params)
      window.open(data?.url)
    }
    catch (e) {}
  }

  return {
    loading,
    lists,
    pagination,
    columns,

    setLoading,
    getLists,
    handleDownload,
  }
}

export function renderType(row: WarningInfo) {
  // @ts-expect-error
  if (row.warningType === '')
    return h('span')
  const level = +row.warningType
  return h(
    ElTag,
    {
      // 等级(0-一般，1-严重，2-紧急)
      type: ['', 'warning', 'danger', ''][
        level
      ] as TagProps['type'],
    },
    () =>
      [
        WARNING_LEVELS_TEXT.NORMAL,
        WARNING_LEVELS_TEXT.SERIOUS,
        WARNING_LEVELS_TEXT.URGENT,
      ][level],
  )
}

export function renderState(row: WarningInfo) {
  // @ts-expect-error
  if (row.state === '')
    return h('span')
  const level = +row.state
  return h(
    ElTag,
    {
      // 状态(0-未处理，1-处理中，2-待审核，3-已处理，4-已忽略)
      type: [
        'danger',
        'success',
        'warning',
        'success',
        'info',
      ][level] as TagProps['type'],
    },
    () =>
      [
        WARNING_STATES_TEXT.UNSETTLED,
        WARNING_STATES_TEXT.SETTLING,
        WARNING_STATES_TEXT.PENDING,
        WARNING_STATES_TEXT.SOLVED,
        WARNING_STATES_TEXT.IGNORED,
      ][level],
  )
}
